<?php

namespace app\admin\controller;
use think\facade\View;
use think\facade\Lang;
/**
 * ============================================================================
 * DSShop单店铺商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Rechargecard extends AdminControl
{
    const EXPORT_SIZE = 100;
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'admin/lang/'.config('lang.default_lang').'/rechargecard.lang.php');
    }

    public function index()
    {
        $rechargecard_model = model('rechargecard');
        $condition = array();

        if (request()->isGet()) {
            $sn = trim((string)input('param.sn'));
            $batchflag = trim((string)input('param.batchflag'));
            $state = input('param.state');
            if (strlen($sn) > 0) {
                $condition[] = array('rc_sn','like', "%{$sn}%");
            }

            if (strlen($batchflag) > 0) {
                $condition[] = array('rc_batchflag','like', "%{$batchflag}%");
            }

            if ($state == '0' || $state == '1') {
                $condition[] = array('rc_state','=',$state);
            }
        }

        $cardList = $rechargecard_model->getRechargecardList($condition, 20);

        View::assign('card_list', $cardList);
        View::assign('show_page', $rechargecard_model->page_info->render());
        $this->setAdminCurItem('index');
        return View::fetch();
    }

    public function add_card()
    {
        if (!request()->isPost()) {
            return View::fetch();
        }
        else {
            $denomination = (float)input('post.denomination');
            if ($denomination < 0.01) {
                $this->error('面额不能小于0.01');
            }
            if ($denomination > 1000) {
                $this->error('面额不能大于1000');
            }

            $snKeys = array();

            switch (input('post.type')) {
                case '0':
                    $total = (int)input('post.total');
                    if ($total < 1 || $total > 5000) {
                        $this->error('总数只能是1~5000之间的整数');
                    }
                    $prefix = (string)input('post.prefix');
                    if (!preg_match('/^[0-9a-zA-Z]{0,16}$/', $prefix)) {
                        $this->error('前缀只能是16字之内字母数字的组合');
                    }
                    while (count($snKeys) < $total) {
                        $snKeys[$prefix . md5(uniqid(mt_rand(), true))] = null;
                    }
                    break;

                case '1':
                    $f = $_FILES['_textfile'];
                    if (!$f || $f['error'] != 0) {
                        $this->error('文件上传失败');
                    }
                    if (!is_uploaded_file($f['tmp_name'])) {
                        $this->error('未找到已上传的文件');
                    }
                    foreach (file($f['tmp_name']) as $sn) {
                        $sn = trim($sn);
                        if (preg_match('/^[0-9a-zA-Z]{1,50}$/', $sn))
                            $snKeys[$sn] = null;
                    }
                    break;

                case '2':
                    foreach (explode("\n", (string)input('post.manual')) as $sn) {
                        $sn = trim($sn);
                        if (preg_match('/^[0-9a-zA-Z]{1,50}$/', $sn))
                            $snKeys[$sn] = null;
                    }
                    break;

                default:
                    $this->error(lang('param_error'));
                    exit;
            }

            $totalKeys = count($snKeys);
            if ($totalKeys < 1 || $totalKeys > 9999) {
                $this->error('只能在一次操作中增加1~9999个充值卡号');
            }

            if (empty($snKeys)) {
                $this->error('请输入至少一个合法的卡号');
            }

            $snOccupied = 0;
            $rechargecard_model = model('rechargecard');

            // chunk size = 50
            foreach (array_chunk(array_keys($snKeys), 50) as $snValues) {
                foreach ($rechargecard_model->getOccupiedRechargecardSNsBySNs($snValues) as $sn) {
                    $snOccupied++;
                    unset($snKeys[$sn]);
                }
            }

            if (empty($snKeys)) {
                $this->error('操作失败，所有新增的卡号都与已有的卡号冲突');
            }

            $batchflag = input('post.batchflag');
            $adminName = $this->admin_info['admin_name'];
            $ts = TIMESTAMP;

            $snToInsert = array();
            foreach (array_keys($snKeys) as $sn) {
                $snToInsert[] = array(
                    'rc_sn' => $sn, 'rc_denomination' => $denomination, 'rc_batchflag' => $batchflag, 'rc_admin_name' => $adminName,
                    'rc_tscreated' => $ts,
                );
            }

            if (!$rechargecard_model->addRechargecardAll($snToInsert)) {
                $this->error(lang('ds_common_op_fail'));
            }

            $countInsert = count($snToInsert);
            $this->log("新增{$countInsert}张充值卡（面额￥{$denomination}，批次标识“{$batchflag}”）");

            $msg = lang('ds_common_op_succ');
            if ($snOccupied > 0)
                $msg .= "有 {$snOccupied} 个卡号与已有的未使用卡号冲突";
            dsLayerOpenSuccess($msg);
        }
    }


    /**
     * 删除平台充值卡
     */
    public function del_card() {
        $rechargecard_model= model('rechargecard');
        $rc_id = input('param.rc_id');
        $rc_id_array = ds_delete_param($rc_id);
        if($rc_id_array === FALSE){
            ds_json_encode(10001, lang('param_error'));
        }
        $condition = array();
        $condition[] = array('rc_id','in', $rc_id_array);
        $condition[] = array('rc_state','=',0);
        $result =$rechargecard_model->delRechargecard($condition);
        if ($result) {
            ds_json_encode(10000, lang('ds_common_del_succ'));
        } else {
            ds_json_encode(10001, lang('ds_common_del_fail'));
        }
    }


    /**
     * 导出
     */
    public function export_step1()
    {
        $rechargecard_model = model('rechargecard');
        $condition = array();

        if (request()->isPost()) {
            $sn = trim((string)input('param.sn'));
            $batchflag = trim((string)input('param.batchflag'));
            $state = trim((string)input('param.state'));

            if (strlen($sn) > 0) {
                $condition[] = array('rc_sn','like', "%{$sn}%");
                View::assign('sn', $sn);
            }

            if (strlen($batchflag) > 0) {
                $condition[] = array('rc_batchflag','like', "%{$batchflag}%");
                View::assign('batchflag', $batchflag);
            }

            if ($state === '0' || $state === '1') {
                $condition[] = array('rc_state','=',$state);
                View::assign('state', $state);
            }
        }

        if (!is_numeric(input('param.page'))) {
            $count = $rechargecard_model->getRechargecardCount($condition);
            $export_list = array();
            if ($count > self::EXPORT_SIZE) {    //显示下载链接
                $page = ceil($count / self::EXPORT_SIZE);
                for ($i = 1; $i <= $page; $i++) {
                    $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                    $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                    $export_list[$i] = $limit1 . ' ~ ' . $limit2;
                }
                View::assign('export_list', $export_list);
                return View::fetch('/public/excel');
            }
            else {    //如果数量小，直接下载
                $data = $rechargecard_model->getRechargecardList($condition, 0,self::EXPORT_SIZE);

                $this->createExcel($data);
            }
        }
        else {    //下载
            $limit1 = (input('param.page') - 1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;

            $data = $rechargecard_model->getRechargecardList($condition, $limit2);

            $this->createExcel($data);
        }
    }

    /**
     * 生成excel
     *
     * @param array $data
     */
    private function createExcel($data = array())
    {
        $excel_obj = new \excel\Excel();
        $excel_data = array();
        //设置样式
        $excel_obj->setStyle(array(
                                 'id' => 's_title', 'Font' => array('FontName' => '宋体', 'Size' => '12', 'Bold' => '1')
                             ));
        //header
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '充值卡卡号');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '批次标识');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '面额(元)');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '发布管理员');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '发布时间');
        $excel_data[0][] = array('styleid' => 's_title', 'data' => '领取人');

        //data
        foreach ((array)$data as $k => $v) {
            $tmp = array();
            $tmp[] = array('data' => "\t" . $v['rc_sn']);
            $tmp[] = array('data' => "\t" . $v['rc_batchflag']);
            $tmp[] = array('data' => "\t" . $v['rc_denomination']);
            $tmp[] = array('data' => "\t" . $v['rc_admin_name']);
            $tmp[] = array('data' => "\t" . date('Y-m-d H:i:s', $v['rc_tscreated']));
            if ($v['rc_state'] == 1 && $v['member_id'] > 0 && $v['rc_tsused'] > 0) {
                $tmp[] = array('data' => "\t" . $v['member_name']);
            }
            else {
                $tmp[] = array('data' => "\t-");
            }
            $excel_data[] = $tmp;
        }
        $excel_data = $excel_obj->charset($excel_data, CHARSET);
        $excel_obj->addArray($excel_data);
        $excel_obj->addWorksheet($excel_obj->charset('充值卡', CHARSET));
        $excel_obj->generateXML($excel_obj->charset('充值卡', CHARSET) . input('param.page') . '-' . date('Y-m-d-H', TIMESTAMP));
    }


    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index', 'text' => '列表', 'url' => url('Rechargecard/index')
            ), array(
                'name' => 'add_card', 'text' => '新增','url' =>"javascript:dsLayerOpen('".url('Rechargecard/add_card')."','新增')"
            ),
        );
        return $menu_array;
    }
}